<template>
    <div class="app-container">

        <el-card>
            <el-form v-show="state.showSearch" ref="queryRef" :model="state.queryParams" :inline="true">
                <!-- <el-form-item label="系列名称" prop="dictType">
                    <el-select v-model="state.queryParams.seriesTitle" style="width: 200px">
                        <el-option v-for="item in seriesOptions" :key="item.seriesId" :label="item.seriesName"
                            :value="item.seriesName" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="锻炼动作" prop="dictLabel">
                    <el-input v-model="state.queryParams.dictLabel" placeholder="请输入动作名称" clearable style="width: 200px"
                        @keyup.enter="getDataList" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="getDataList">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card style="margin-top: 20px;">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button v-hasPermi="['exercise:action:add']" type="primary" plain icon="Plus"
                        @click="groupHandle()">新增组</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getDataList"></right-toolbar>
            </el-row>

            <el-table v-if="refreshTable" v-loading="state.dataListLoading" :data="state.rows" row-key="groupId"
                :default-expand-all="isExpandAll" :tree-props="{ children: 'actionList' }">
                <el-table-column label="所属分组" align="center" width="100">
                    <template #default="scope">
                        {{scope.row.groupNum?'第'+numberToWords(scope.row.groupNum)+'组':''}}
                    </template>
                </el-table-column>
                <el-table-column label="动作编码" align="center" prop="actionId" />
                <el-table-column label="动作名称" align="center" prop="name" />
                <el-table-column label="时长(秒)" align="center" prop="time" />
                <el-table-column label="重复次数" align="center" prop="repeats" />
                <el-table-column label="会员限制" align="center" prop="level" />
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip :content="scope.row.actionList?'编辑分组':'编辑动作'" placement="top">
                            <el-button v-if="scope.row.actionList" v-hasPermi="['exercise:group:edit']" link
                                type="primary" icon="Edit" @click="groupHandle(scope.row.groupId)"></el-button>
                            <el-button v-else v-hasPermi="['exercise:action:edit']" link type="primary" icon="Edit"
                                @click="addOrUpdateHandle(scope.row.groupId,scope.row.actionId)"></el-button>
                        </el-tooltip>
                        <el-tooltip :content="scope.row.actionList?'删除分组':'删除动作'" placement="top">
                            <el-button v-if="!scope.row.actionList" v-hasPermi="['exercise:action:remove']" link
                                type="danger" icon="Delete" @click="deleteHandle(scope.row.actionId)"></el-button>
                            <el-button v-else v-hasPermi="['exercise:action:remove']" link type="danger" icon="Delete"
                                @click="deleteGroupHandle(scope.row.groupId)"></el-button>
                        </el-tooltip>
                        <el-tooltip v-if="!scope.row.actionList" content="展开" placement="top">
                            <el-button v-hasPermi="['exercise:action:query']" link type="success" icon="Switch"
                                @click="openDrawer(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip v-else content="新增动作" placement="top">
                            <el-button v-hasPermi="['exercise:action:add']" link type="success" icon="Plus"
                                @click="addOrUpdateHandle(scope.row.groupId,undefined)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="state.total > 0" v-model:page="state.pageNum" v-model:limit="state.pageSize"
                :total="state.total" @pagination="getDataList" />
        </el-card>

        <AddOrEdit ref="addOrUpdateRef" @refreshDataList="getDataList" :seriesId="routeSId"></AddOrEdit>

        <el-dialog v-model="open" :title="title" width="500" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" label-width="150px">
                <el-form-item v-if="form.groupId" label="组别" prop="groupNum"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <el-input v-model="form.groupNum" placeholder="请输入组别" disabled />
                </el-form-item>

                <el-form-item label="该组动作重复次数" prop="repeats"
                    :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                    <!-- <el-input v-model="form.repeats" placeholder="请输入改组动作的重复次数">
                        <template #append>(次)</template>
                    </el-input> -->
                    <el-input-number v-model="form.repeats" :min="1" :max="99" style="width: 310px"
                        controls-position="right" />
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 展开-查看图片 -->
        <el-drawer v-model="drawer" :direction="direction">
            <template #header>
                <h4 class="bold">锻炼动作</h4>
            </template>
            <template #default>
                <el-descriptions :size="size" :column="1" border>
                    <el-descriptions-item>
                        <template #label>
                            <div class="bold">
                                动作名称
                            </div>
                        </template>
                        {{openAction?.name}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                        <template #label>
                            <div class="bold">
                                封面图片
                            </div>
                        </template>
                        <el-image style="width: 200px; height: 200px" :src="openAction?.imgPath" :zoom-rate="1.2"
                            :max-scale="7" :min-scale="0.2" :initial-index="4" fit="contain" />
                    </el-descriptions-item>
                </el-descriptions>
            </template>
        </el-drawer>

    </div>
</template>

<script setup name="Action" lang="ts">
    import { useRoute } from 'vue-router';
    import { IHooksOptions } from '@/hooks/hooksinterface'
    import { useCrud } from '@/hooks/hooksservice'
    import { ref, reactive, getCurrentInstance, ComponentInternalInstance, nextTick } from 'vue'
    import { listAction, delAction, getGroup, updateGroup, addGroup, delGroup } from '@/api/app/exercise'
    import AddOrEdit from './action-add-or-edit.vue'
    import { ComponentSize, DrawerProps, ElMessage, FormInstance } from 'element-plus';
    import { ExerciseGroupResp } from '@/types/app/exercise'
    import { numberToWords } from '@transnal-utils/number-to-chinese-words'

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;

    const route = useRoute();

    // const seriesOptions = ref<any[]>([]);

    //得到数据表单form样式对象
    const formRef = ref<FormInstance>();

    // 对话框配置
    const open = ref(false);
    const title = ref('');

    // 抽屉控制
    const drawer = ref(false)
    const direction = ref<DrawerProps['direction']>('rtl')
    const openAction : any | undefined = ref(undefined)
    // const title = ref("")
    const size = ref<ComponentSize>('large')

    //刷新表格
    const refreshTable = ref(true);
    //是否展开节点
    const isExpandAll = ref(true);

    const routeSId = route.params && route.params.seriesId

    const form = ref<ExerciseGroupResp>({
        groupId: undefined,
        sid: undefined,
        groupNum: undefined,
        repeats: 1
    })

    const state : IHooksOptions = reactive({
        primaryKey: 'actionId',
        pageNum: 1,
        pageSize: 10,
        isPage: false,
        queryParams: {
            seriesId: routeSId,
            seriesTitle: '',
        },
        queryApi: listAction,
        deleteApi: delAction
    })

    const { getDataList, resetQuery, deleteHandle } = useCrud(state)


    // 调用新增或修改页面的方法
    const addOrUpdateRef = ref()
    //新增或修改的时候传递id
    const addOrUpdateHandle = (gid : number, aid ?: number) => {
        //调用它里面的init方法
        addOrUpdateRef.value.init(gid, aid)
    }

    /** 返回按钮操作 */
    function handleClose() {
        const obj = { path: '/app/exercise/series' };
        proxy!.$tab.closeOpenPage(obj);
    }

    //对话框取消按钮
    const cancel = () => {
        open.value = false;
        resetFrom();
    };

    //对话框保存按钮
    const submitForm = () => {
        formRef.value?.validate((valid : boolean) => {
            // 验证不成功
            if (!valid) {
                return false
            }

            // 修改
            if (form.value.groupId) {
                updateGroup(form.value).then(() => {
                    ElMessage.success({
                        message: '修改成功',
                        duration: 500,
                        onClose: () => {
                            // 关闭对话框
                            open.value = false
                            //调用重新查询数据操作
                            // emit('refreshDataList')
                            getDataList()
                        }
                    });

                })
            } else {
                //新增
                form.value.sid = routeSId
                addGroup(form.value).then(() => {
                    ElMessage.success({
                        message: '新增成功',
                        duration: 500,
                        onClose: () => {
                            // 关闭对话框
                            open.value = false
                            //调用重新查询数据操作
                            // emit('refreshDataList')
                            getDataList()
                        }
                    });

                })
            }

        })
    };

    //判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
    const groupHandle = (id ?: number) => {
        open.value = true
        // 重置表单数据
        resetFrom();
        // id 存在则为修改
        title.value = "新增动作组"
        if (id) {
            title.value = "动作组-编辑"
            getGroup(id).then(resp => {
                const data : ExerciseGroupResp = resp.data;
                //转换为字符串{"seriesId":1}
                const str = JSON.stringify(data);
                //再一次把字符串还原成对象
                form.value = JSON.parse(str);
            })
        }
    }

    // 删除分组
    function deleteGroupHandle(groupId ?: any) {

        proxy?.$modal
            .confirm('是否确认删除分组？')
            .then(function () {
                return delGroup(groupId);
            })
            .then(() => {
                getDataList();
                proxy!.$modal.msgSuccess('删除成功');
            })
            .catch((e : any) => {
                console.log(e);
            });
    }

    // 重置表单
    const resetFrom = () => {
        // 清空表单样式
        if (formRef.value) {
            formRef.value.resetFields();
        }
        // 重置值
        form.value = {
            groupId: undefined,
            groupNum: undefined,
            repeats: 1
        };
    };

    /** 展开/折叠操作 */
    function toggleExpandAll() {
        refreshTable.value = false;
        isExpandAll.value = !isExpandAll.value;
        nextTick(() => {
            refreshTable.value = true;
        });
    }

    const openDrawer = (row : any) => {
        openAction.value = row
        drawer.value = true
    }
</script>

<style scope>
    .bold {
        font-weight: 600;
    }
</style>
